package com.ecoolex.chinadutyfree.retailer.core.manager;

import com.ecoolex.chinadutyfree.retailer.core.dao.UserOrderDataDAO;
import com.ecoolex.chinadutyfree.retailer.entity.UserOrderData;
import com.ecoolex.chinadutyfree.retailer.enums.DirectMailGoodsOrderStatus;
import com.ecoolex.framework.common.pojo.Page;
import com.ecoolex.framework.common.pojo.Pagination;
import com.ecoolex.framework.common.pojo.Sorting;
import com.ecoolex.framework.common.pojo.Sortings;
import com.ecoolex.framework.common.util.DateUtil;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserOrderDataManager {
    @Autowired
    private UserOrderDataDAO dao;
    
    /**
	 * 用户每日订单数据。定时任务每天零点执行一次
	 */
	public Long userOrderData(String updateUser) {
		// 获取当前日期前一天的日期字符串
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		Date now = Date.from(Instant.now());
		calendar.setTime(now);
		calendar.add(Calendar.DATE, -1);
		String yesterday = format.format(calendar.getTime());
		// 获取当前日期
		Date today = Date.from(Instant.now());
		DateUtil.cleanTimePart(today);
		return dao.add(today, updateUser, now, updateUser, now, UserOrderData.NOT_DELETED, yesterday,
			DirectMailGoodsOrderStatus.PAID.real(),
			DirectMailGoodsOrderStatus.COMPLETE.real(),
			DirectMailGoodsOrderStatus.WAIT_RECECEIVE.real(),
			DirectMailGoodsOrderStatus.AFTER_SALES.real());
	}
	
	/**
	 * 根据日期筛选用户订单增量数据
	 * 
	 * @param startDate
	 * @param endDate
	 * @param UserName
	 * @param currPage
	 * @param pageSize
	 * @return
	 */
	public Pagination<UserOrderData> queryUserOrder(Date startDate, Date endDate, Integer userId, Sorting[] sorts, Page page) {
		return Pagination.create(page,
			dao.countByDate(startDate, endDate, userId),
			() -> dao.queryByDate(startDate, endDate, userId, Sortings.builder(sorts).toSql(), page));
	}
}